package com.pkk.cloud.support.oauth2.config.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pkk.components.rpc.response.util.ResponseUtil;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

/**
 * @Description: 授权失败(forbidden)时返回信息
 * @Param: null
 * @return:
 * @Author: peikunkun
 * @Date: 2020/3/19 0019 下午 2:35
 */
public class Oauth2AccessDeniedHandler implements AccessDeniedHandler {

  @Autowired
  private ObjectMapper objectMapper;

  /**
   * @Description: 授权失败的处理返回响应信息
   * @Param: request
   * @Param response
   * @Param accessDeniedException
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/3/19 0019 下午 2:36
   */
  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response,
      AccessDeniedException accessDeniedException) throws IOException, ServletException {
    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().write(objectMapper.writeValueAsString(ResponseUtil.error(accessDeniedException.getMessage())));
  }


}
